package com.twu.biblioteca.dao;

import com.twu.biblioteca.model.Movie;
import com.twu.biblioteca.model.User;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by minggong on 7/19/14.
 */
public class UserResource {
    public List<User> users;
    private int generateId = 1;

    public UserResource(String file) {
        users = new ArrayList<User>();
        loadUser(file);
    }
    public User authenticate(String libraryNumber, String password) {
        for (User user : users) {
            if (user.authenticate(libraryNumber, password)) {
                return user;
            }
        }
        return null;
    }

    private void loadUser(String file) {
        try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
            String line;
            bufferedReader.readLine();//skip first title line.
            while((line = bufferedReader.readLine()) != null) {
                String[] content = line.split(",");
                if (content.length != 5) continue;
                users.add(new User(generateId++, content[0], content[1], content[2], content[3], content[4]));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public User getUserById(int id) {
        for (User user :users) {
            if (user.getId() == id) {
                return user;
            }
        }
        return null;
    }
}
